import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class SetNicknamePage extends StatefulWidget {
  String name;

  SetNicknamePage({Key key, this.name}) : super(key: key);

  @override
  _SetNicknamePageState createState() => _SetNicknamePageState();
}

class _SetNicknamePageState extends State<SetNicknamePage> {
  TextEditingController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TextEditingController(text: widget.name);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(
        context,
        "设置昵称",
        rightText: "完成",
        isRightTextBtn: true,
        rightCallback: () {
          String nickName = _controller.text.toString().trim();
          if (nickName.length == 0) {
            toast("请输入昵称");
            return;
          }
          EasyLoading.show(status: "修改中...");
          TencentImSDKPlugin.v2TIMManager
              .setSelfInfo(
            userFullInfo: V2TimUserFullInfo.fromJson(
              {
                "nickName": nickName,
              },
            ),
          )
              .then((value) {
            print('----value---------${json.encode(value)}');
            if (value.code == 0) {
              onSelfInfoUpdated();
              _updateUserInfo(nickName);
            } else {
              EasyLoading.dismiss();
            }
          });

          //todo 需要走服务器流程
          print(widget.name);
        },
      ),
      body: Column(
        children: [
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Container(
              padding: EdgeInsets.only(left: 20),
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(15),
                  top: ScreenUtil().setHeight(10),
                  right: ScreenUtil().setWidth(15)),
              decoration: BoxDecoration(
                  color: Color.fromRGBO(241, 241, 241, 1),
                  borderRadius: BorderRadius.circular(6)),
              child: TextField(
                controller: _controller,
                cursorColor: Colors.lightBlueAccent,
                keyboardType: TextInputType.name,
                autofocus: false,
                maxLines: 1,
                maxLength: 12,
                decoration: InputDecoration(
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    EasyLoading.dismiss();
    super.dispose();
  }

  void onSelfInfoUpdated() async {
    //自己信息更新，从新获取自己的信息；
    V2TimValueCallback<String> usercallback =
        await TencentImSDKPlugin.v2TIMManager.getLoginUser();
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [usercallback.data]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  _updateUserInfo(String nickName) async {
    try {
      UserInfoModel userInfoModel =
          await UserInfoDao.updateUserInfo("nickname", nickName);
      EasyLoading.dismiss();
      if (userInfoModel.resultCode == 0) {
        toast(userInfoModel.resultMsg);
        return;
      }
      Navigator.of(context).pop();
      toast("修改成功");
    } catch (e) {
      print(e);
      _error();
    }
  }

  void _error() {
    toast("修改失败");
    EasyLoading.dismiss();
  }
}
